package com.ruoyi.employee.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.customer.service.ICustomerUserService;
import com.ruoyi.employee.domain.EmployeeApply;
import com.ruoyi.employee.domain.EmployeeStatic;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.mapper.EmployeeApplyMapper;
import com.ruoyi.employee.service.IEmployeeApplyService;
import com.ruoyi.employee.service.IEmployeeStaticService;
import com.ruoyi.employee.service.IEmployeeUserService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.List;

/**
 * 用户申请店员 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class EmployeeApplyServiceImpl implements IEmployeeApplyService
{

    @Autowired
    private EmployeeApplyMapper employeeApplyMapper;

    @Autowired
    private IEmployeeUserService employeeUserService;

    @Autowired
    private ICustomerUserService customerUserService;

    @Autowired
    private IEmployeeStaticService employeeStaticService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysConfigService configService;

    /**
     * 根据条件分页查询用户申请店员列表
     * 
     * @param user 用户申请店员信息
     * @return 用户申请店员信息集合信息
     */
    @Override
    // @DataScope(deptAlias = "d", userAlias = "u")
    public List<EmployeeApply> selectUserList(EmployeeApply user)
    {
        return employeeApplyMapper.selectUserList(user);
    }

    /**
     * 通过用户申请店员名查询用户申请店员
     * 
     * @param userName 用户申请店员名
     * @return 用户申请店员对象信息
     */
    @Override
    public EmployeeApply selectUserByUserName(String userName)
    {
        return employeeApplyMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户申请店员ID查询用户申请店员
     * 
     * @param userId 用户申请店员ID
     * @return 用户申请店员对象信息
     */
    @Override
    public EmployeeApply selectUserById(Long userId)
    {
        return employeeApplyMapper.selectUserById(userId);
    }

    /**
     * 通过用户申请店员ID查询用户申请店员
     *
     * @param employeeId 店员ID
     * @return 用户申请店员对象信息
     */
    @Override
    public EmployeeApply selectUserByEmployeeId(Long employeeId)
    {
        return employeeApplyMapper.selectUserByEmployeeId(employeeId);
    }

    /**
     * 校验用户申请店员名称是否唯一
     * 
     * @param user 用户申请店员信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(EmployeeApply user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeApply info = employeeApplyMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户申请店员昵称是否唯一
     *
     * @param user 用户申请店员信息
     * @return 结果
     */
    @Override
    public boolean checkNickNameUnique(EmployeeApply user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeApply info = employeeApplyMapper.checkNickNameUnique(user.getNickName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户申请店员关联客户是否唯一
     *
     * @return 结果
     */
    @Override
    public boolean checkCustomerIdUnique()
    {
        Long userId = SecurityUtils.getUserId();
        EmployeeApply info = employeeApplyMapper.checkCustomerIdUnique(userId);
        if (StringUtils.isNotNull(info))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户申请店员信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(EmployeeApply user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeApply info = employeeApplyMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户申请店员信息
     * @return
     */
    @Override
    public boolean checkUserStatusIsAudit(EmployeeApply user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeApply info = employeeApplyMapper.selectUserById(userId);
        if (StringUtils.isNotNull(info) && info.getStatus().equals(UserConstants.STATUS_AUDIT))
        {
            return UserConstants.TRUE_FLAG;
        }
        return UserConstants.FALSE_FLAG;
    }

    /**
     * 新增保存用户申请店员信息
     * 
     * @param user 用户申请店员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(EmployeeApply user)
    {
        // 新增用户申请店员信息
        Long userId = SecurityUtils.getUserId();
        user.setCustomerId(userId);
        user.setStatus(UserConstants.STATUS_AUDIT);
        if(StringUtils.isNotNull(user.getEmployeeId())){
            user.setApplyType("edit");
        }else{
            user.setApplyType("add");
        }
        int rows = employeeApplyMapper.insertUser(user);
        return rows;
    }

    /**
     * 修改保存用户申请店员信息
     * 
     * @param user 用户申请店员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(EmployeeApply user)
    {
        return employeeApplyMapper.updateUser(user);
    }

    /**
     * 修改保存用户申请店员信息
     *
     * @param user 用户申请店员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUserStatus(EmployeeApply user)
    {
        if(user.getStatus().equals(UserConstants.STATUS_APPROVE)){

            EmployeeUser employeeUser = new EmployeeUser();
            if(StringUtils.isNotNull(user.getEmployeeId())){
                // 修改店员资料
                employeeUser = employeeUserService.selectUserById(user.getEmployeeId());
            }else{
                if (!employeeUserService.checkPhoneUniqueByPhone(-1L, user.getPhonenumber()))
                {
                    throw new ServiceException("修改失败：店员手机号已存在");
                }
                employeeUser.setUserName(user.getPhonenumber());
                employeeUser.setPhonenumber(user.getPhonenumber());
                employeeUser.setUserLevel(user.getUserLevel());
                employeeUser.setShopId(user.getShopId());
                employeeUser.setOpenId(user.getOpenId());
                employeeUser.setActive(user.getActive());
            }
            employeeUser.setNickName(user.getNickName());
            employeeUser.setWxId(user.getWxId());
            employeeUser.setSex(user.getSex());
            employeeUser.setAvatar(user.getAvatar());
            employeeUser.setImages(user.getImages());
            employeeUser.setAddress(user.getAddress());
            employeeUser.setAddressCode(user.getAddressCode());
            employeeUser.setBirthday(user.getBirthday());
            employeeUser.setConstellation(user.getConstellation());
            employeeUser.setServiceType(user.getServiceType());
            employeeUser.setTags(user.getTags());
            employeeUser.setUserProfile(user.getUserProfile());
            employeeUser.setSpeech(user.getSpeech());

            if(StringUtils.isNotNull(user.getEmployeeId())){
                // 修改店员资料
                employeeUserService.updateUser(employeeUser);
            }else{
                // 添加新的店员
                String password = configService.selectConfigByKey("sys.user.initPassword");
                employeeUser.setPassword(SecurityUtils.encryptPassword(password));
                employeeUserService.insertUser(employeeUser);

                CustomerUser customerUser = customerUserService.selectUserByOpenId(user.getOpenId());
                if(customerUser != null){
                    customerUser.setIsEmployee(UserConstants.YES);
                    customerUserService.updateUser(customerUser);
                }
            }
        }
        return employeeApplyMapper.updateUser(user);
    }

    /**
     * 批量删除用户申请店员信息
     * 
     * @param userIds 需要删除的用户申请店员ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds)
    {
        return employeeApplyMapper.deleteUserByIds(userIds);
    }
}
